package com.sinoglobal.ningxia.utils;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.sinoglobal.ningxia.R;


import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

/**
 * @title: CrashHandler.java
 * @package com.example.pubilcexception
 * @description: UncaughtException处理类,当程序发生Uncaught异常的时候,有该类来接管程序,并记录发送错误报告.
 * @author yrq
 * @date 2015-1-20 上午9:22:29
 */
public class CrashHandler implements UncaughtExceptionHandler {

	public static final String TAG = "CrashHandler";
	public static String rootPath = "";
	private static final String newLog = "0newLog.txt";
	// 系统默认的UncaughtException处理类
	private Thread.UncaughtExceptionHandler mDefaultHandler;
	// CrashHandler实例
	private static CrashHandler INSTANCE = new CrashHandler();
	// 程序的Context对象
	private static Context mContext;
	// 用来存储设备信息和异常信息
	private LinkedHashMap<String, String> infos = new LinkedHashMap<String, String>();
	// 用于格式化日期,作为日志文件名的一部分
	@SuppressLint("SimpleDateFormat")
	private SimpleDateFormat formatter;
	private static final String URL = "http://192.168.10.86:8080/logpanel/api/logs/save";

	/** 保证只有一个CrashHandler实例 */
	private CrashHandler() {
	}

	/** 获取CrashHandler实例 ,单例模式 */
	public static CrashHandler getInstance() {
		return INSTANCE;
	}

	/**
	 * 初始化
	 * 
	 * @param context
	 */
	public void init(Context context) {
		mContext = context;
		formatter = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss", Locale.getDefault());
		initDir();
		update(rootPath + newLog);
		// 获取系统默认的UncaughtException处理器
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
		// 设置该CrashHandler为程序的默认处理器
		Thread.setDefaultUncaughtExceptionHandler(this);
	}

	/**
	 * 当UncaughtException发生时会转入该函数来处理
	 */
	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		if (!handleException(ex) && mDefaultHandler != null) {
			// 如果用户没有处理则让系统默认的异常处理器来处理
			mDefaultHandler.uncaughtException(thread, ex);
		} else {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				Log.e(TAG, "error : ", e);
			}
			// 退出程序
			android.os.Process.killProcess(android.os.Process.myPid());
			System.exit(1);
		}
	}

	/**
	 * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
	 * 
	 * @param ex
	 * @return true:如果处理了该异常信息;否则返回false.
	 */
	private boolean handleException(Throwable ex) {
		if (ex == null) {
			return false;
		}
		// 使用Toast来显示异常信息
		new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出.", Toast.LENGTH_LONG).show();
				Looper.loop();
			}
		}.start();
		// 收集设备参数信息
		collectDeviceInfo(mContext);
		// 保存日志文件
		saveCrashInfo2File(ex);
		return true;
	}

	/**
	 * 收集设备参数信息
	 * 
	 * @param ctx
	 */
	public void collectDeviceInfo(Context ctx) {
		try {
			PackageManager pm = ctx.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
			if (pi != null) {
				String versionName = pi.versionName == null ? "null" : pi.versionName;
				String versionCode = pi.versionCode + "";
				infos.put("versionName", versionName);
				infos.put("versionCode", versionCode);
			}
		} catch (NameNotFoundException e) {
			Log.e(TAG, "an error occured when collect package info", e);
		}
		// Field[] fields = Build.class.getDeclaredFields();
		// for (Field field : fields) {
		// try {
		// field.setAccessible(true);
		// infos.put(field.getName(), field.get(null).toString());
		// Log.d(TAG, field.getName() + " : " + field.get(null));
		// } catch (Exception e) {
		// Log.e(TAG, "an error occured when collect crash info", e);
		// }
		// }
		infos.put("moudel", Build.MODEL);
		infos.put("manufacturer", Build.MANUFACTURER);
		infos.put("brand", Build.BRAND);
	}

	/**
	 * 保存错误信息到文件中
	 * 
	 * @param ex
	 * @return 返回文件名称,便于将文件传送到服务器
	 */
	private void saveCrashInfo2File(Throwable ex) {
		// 将获取到的手机信息添加到StringBuffer中
		StringBuffer sb = new StringBuffer();
		String time = formatter.format(new Date());
		infos.put("createTime", time);
		for (Map.Entry<String, String> entry : infos.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			sb.append(key + "=" + value + "<br>");
		}
		// 将错误信息添加到StringBuffer中
		Writer writer = new StringWriter();
		PrintWriter printWriter = new PrintWriter(writer);
		ex.printStackTrace(printWriter);
		Throwable cause = ex.getCause();
		while (cause != null) {
			cause.printStackTrace(printWriter);
			cause = cause.getCause();
//			printWriter.append("<br>");
		}
		printWriter.close();
		String result = writer.toString().replace("	", "<br>");
		sb.append(result);

		// 将StringBuffer中的内容保存到-- 以项目名拼上时间的txt文件-- 中
		try {
			// 定义保存错误信息的文件名--》名拼上时间
			String fileName = time + ".txt";
			File f = new File(rootPath);
			if (!f.exists()) {
				f.mkdirs();
			}
			writeFileCache(rootPath + newLog, sb.toString());
			writeFileCache(rootPath + fileName, sb.toString());
		} catch (Exception e) {
			Log.e(TAG, "an error occured while writing file...", e);
		}
	}

	/**
	 * @author Administrator
	 * @methods initDir
	 * @description 初始化目录
	 * @date 2015-1-20 下午5:14:59 参数说明
	 */
	private void initDir() {
		// 判断sd卡是否挂载
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			// 定义保存错误信息的文件保存路径
			rootPath = Environment.getExternalStorageDirectory() + File.separator + "0sinoCrash" + File.separator
					+ mContext.getString(R.string.app_name) + File.separator;
		}
	}

	/**
	 * 
	 * @author kkai
	 * @methods update
	 * @description 上传错误日志
	 * @date 2015-1-20 下午12:03:59
	 * @param file
	 * @return 参数说明
	 */
	public void update(String path) {
		if (TextUtils.isEmpty(path)) {
			return;
		}
		final File file = new File(path);
		if (!file.exists()) {
			return;
		}
		// final ProgressDialog pd = ProgressDialog.show(mContext, "请稍候",
		// "正在上传日志信息...");
		new AsyncTask<Void, Void, Result>() {
			@Override
			protected Result doInBackground(Void... params) {

				System.out.println("上传错误信息");
				try {
					return post(loadFileCache(file));
				} catch (Exception e) {
					e.printStackTrace();
				}
				return new Result("9999", "上传失败");
			}

			@Override
			protected void onPostExecute(Result result) {
				super.onPostExecute(result);
				// pd.cancel();
				if ("0000".equals(result.getRescode())) {
					showMessage("上传成功，请登录服务器查看错误日志");
					deleteCache(rootPath + newLog);
				} else {
					showMessage("上传失败，请重新打开应用或联系开发人员,error= " + result.getResdesc());
				}
			}
		}.execute();
	}

	/**
	 * @author Administrator
	 * @methods post
	 * @description 普通键值对post
	 * @date 2015-1-20 下午5:15:23
	 * @param url
	 * @param params
	 * @throws Exception
	 *             参数说明 appName; 项目名 system; 系统 version; 版本 logInfo; 错误信息
	 *             createDate; 时间
	 */
	public Result post(String content) throws Exception {
		HttpPost httpost = new HttpPost(URL);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		try {
			PackageManager pm = mContext.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
			if (pi != null) {
				String versionName = pi.versionName == null ? "null" : pi.versionName;
				nvps.add(new BasicNameValuePair("version", versionName));
			}
		} catch (NameNotFoundException e) {
			Log.e(TAG, "an error occured when collect package info", e);
		}
		nvps.add(new BasicNameValuePair("appName", mContext.getString(R.string.app_name)));
		nvps.add(new BasicNameValuePair("system", "android"));
		nvps.add(new BasicNameValuePair("logInfo", content));

		httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
		HttpClient httpclient = new DefaultHttpClient();
		Result result = null;
		try {
			HttpResponse response = httpclient.execute(httpost);
			if (response != null) {
				int statusCode = response.getStatusLine().getStatusCode();
				switch (statusCode) {
				case HttpStatus.SC_OK:
					String json = EntityUtils.toString(response.getEntity(), "UTF-8");
					System.out.println(json);
					JSONObject obj = new JSONObject(json);
					result = new Result();
					result.setRescode(obj.getString("rescode"));
					result.setResdesc(obj.getString("resdesc"));
					break;
				case HttpStatus.SC_FORBIDDEN: // 验证未通过
					break;
				case HttpStatus.SC_NOT_FOUND: // 请求错误
					break;
				}
			}
		} finally {

		}
		return result;
	}

	/**
	 * @author Administrator
	 * @methods deleteCache
	 * @description 删除文件
	 * @date 2015-1-20 下午5:15:35
	 * @param path
	 *            参数说明
	 */
	private static void deleteCache(String path) {
		File file = new File(path);
		if (file.exists()) { // 判断文件是否存在
			if (file.isFile()) { // 判断是否是文件
				file.delete(); // delete()方法 你应该知道 是删除的意思;
				System.out.println("删除文件");
			}
		}
	}

	/**
	 * @author sbk
	 * @createdate 2014-3-17 下午8:10:05
	 * @Description: 写入缓存
	 * @param fileName
	 * @param content
	 * 
	 */
	public static void writeFileCache(String fileName, String content) {
		File temp = new File(fileName);
		DataOutputStream dos = null;
		try {
			dos = new DataOutputStream(new FileOutputStream(temp));
			dos.writeUTF(content);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				dos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @author sbk
	 * @createdate 2014-3-17 下午8:09:45
	 * @Description: 加载缓存，缓存不存在时返回-1
	 * @param fileName
	 * @return
	 * 
	 */
	public static String loadFileCache(File file) {
		String content = "";
		if (file.exists()) {
			try {
				content = new DataInputStream(new FileInputStream(file)).readUTF();
			} catch (Exception e) {
				e.printStackTrace();
				return content;
			}
		}
		return content;
	}

	private static void showMessage(String text) {
		Toast.makeText(mContext, text, Toast.LENGTH_LONG).show();
	}

	/**
	 * @title: CrashHandler.java
	 * @package com.example.pubilcexception
	 * @description: 返回参数
	 * @author kkai
	 * @date 2015-1-22 下午5:49:41
	 */
	class Result {
		public Result() {
			super();
		}

		public Result(String rescode, String resdesc) {
			super();
			this.rescode = rescode;
			this.resdesc = resdesc;
		}

		String rescode;
		String resdesc;

		public String getRescode() {
			return rescode;
		}

		public void setRescode(String rescode) {
			this.rescode = rescode;
		}

		public String getResdesc() {
			return resdesc;
		}

		public void setResdesc(String resdesc) {
			this.resdesc = resdesc;
		}
	}

}
